import { login, getUserInfo } from '@/api/user'
import { constantRoutes, resetRouter } from '@/router'
import { getToken, removeToken, setToken } from '@/utils/auth'

const state = {
  token: getToken(),
  userInfo: {},
  routes: constantRoutes // 默认静态路由
}
const mutations = {
  // 渲染左侧菜单路由
  setRoutes(state, newRoutes) {
    state.routes = [...constantRoutes, ...newRoutes]
  },
  setToken(state, newToken) {
    state.token = newToken
    setToken(newToken)
  },
  delToken(state) {
    state.token = null
    removeToken()
  },
  setUserInfo(state, userInfo) {
    state.userInfo = userInfo
  }
}
const actions = {
  async loginAsync(context, data) {
    const res = await login(data)
    context.commit('setToken', res)
  },
  async getUserInfoAsync(context) {
    const res = await getUserInfo()
    context.commit('setUserInfo', res)
    return res
  },
  logout(context) {
    // 清除token
    context.commit('delToken')
    // 清除用户信息
    context.commit('setUserInfo', {})
    // 重置路由
    resetRouter()
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

